﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO;
using System.Collections;

namespace HttpWorkRequestNS
{
    public class LoginRespObj
    {
        public string access_token { get; set; }
        public string token_type { get; set; }
        public string refresh_token { get; set; }
        public string expires_in { get; set; }
        public string scope { get; set; }
        public string expiration { get; set; }
        public string userId { get; set; }
    }

    public class DictionaryRespItem
    {
        public string grouping { get; set; }
        public string title { get; set; }
        public string code { get; set; }
        public string sequence { get; set; }
    }

    public class DictionaryRespList
    {
        public IList<DictionaryRespItem> data;
        public int code;
        public string msg;
        public string dev;
        public long timestamp;
    }

    public class NoDataRespObj
    {
        public int code { get; set; }
        public object msg { get; set; }
        public object dev { get; set; }
        public object data { get; set; }
        public long timestamp { get; set; }
    }

    public class NetWorkUtils
    {
        private static string m_sHeaderInf = "";

        public static void SetHeaderInfo(string info)
        {
            m_sHeaderInf = info;
        }


        public static string HttpPostNetData(string sUri, System.Collections.Generic.Dictionary<string, string> mapData)
        {
            string urlStr = string.Format("http://123.206.73.108:90/api/{0}", sUri);
            HttpWebRequest request = WebRequest.Create(urlStr) as HttpWebRequest;
            //添加请求头信息
            if (m_sHeaderInf.Length > 5)
            {
                request.Headers.Add("Authorization", m_sHeaderInf);
            }
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            //
            int index = 0;
            StringBuilder builder = new StringBuilder();
            foreach (string key in mapData.Keys)
            {
                if (index > 0)
                {
                    builder.AppendFormat("&{0}={1}", key, mapData[key]);
                }
                else
                {
                    builder.AppendFormat("{0}={1}", key, mapData[key]);
                }
                index++;
            }
            byte[] data = Encoding.GetEncoding("utf-8").GetBytes(builder.ToString());
            //
            using (Stream stream = request.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
            }
            var response = (request.GetResponse() as HttpWebResponse);
            string result = "";
            //获取响应内容
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            response.Close();
            return result;
        }

        public static string HttpPostMultiPartData(string url, string file, string paramName, string contentType, System.Collections.Generic.Dictionary<string, string> stringDict)
        {
            var result = string.Empty;
            var boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
            var boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

            var request = (HttpWebRequest)WebRequest.Create(url);
            request.ContentType = "multipart/form-data; boundary=" + boundary;
            request.Method = "POST";
            request.KeepAlive = true;
            request.Credentials = CredentialCache.DefaultCredentials;

            var stream = request.GetRequestStream();
            var template = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
            foreach (string key in stringDict.Keys)
            {
                stream.Write(boundarybytes, 0, boundarybytes.Length);
                var formitem = string.Format(template, key, stringDict[key]);
                var formitembytes = Encoding.UTF8.GetBytes(formitem);
                stream.Write(formitembytes, 0, formitembytes.Length);
            }
            stream.Write(boundarybytes, 0, boundarybytes.Length);

            var headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
            var header = string.Format(headerTemplate, paramName, file, contentType);
            var headerbytes = Encoding.UTF8.GetBytes(header);
            stream.Write(headerbytes, 0, headerbytes.Length);

            var fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
            var buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
            {
                stream.Write(buffer, 0, bytesRead);
            }
            fileStream.Close();

            var bytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
            stream.Write(bytes, 0, bytes.Length);
            stream.Close();

            WebResponse wresp = null;
            try
            {
                wresp = request.GetResponse();
                var stream2 = wresp.GetResponseStream();
                var reader2 = new StreamReader(stream2);
                result = reader2.ReadToEnd();
            }
            catch (Exception ex)
            {
                if (wresp != null)
                {
                    wresp.Close();
                    wresp = null;
                }
            }
            finally
            {
                request = null;
            }
            return result;


        }


        public static string HttpGetNetData(string sUrl, System.Collections.Generic.Dictionary<string, string> dicParam)
        {
            string result = "";
            //parameter的组串
            StringBuilder builder = new StringBuilder();
            int index = 0;
            foreach (string keyStr in dicParam.Keys)
            {
                if (index > 0)
                {
                    builder.AppendFormat("&{0}={1}", keyStr, dicParam[keyStr]);
                }
                else
                {
                    builder.AppendFormat("{0}={1}", keyStr, dicParam[keyStr]);
                }
                index++;
            }
            string url = string.Format("http://123.206.73.108:90/api/{0}?{1}", sUrl, builder.ToString());
            //
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            //添加请求头信息
            request.Headers.Add("Authorization", m_sHeaderInf);
            request.Method = "GET";
            request.ContentType = "application/x-www-form-urlencoded";
            //
            try
            {
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                Stream responseStream = response.GetResponseStream();
                StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
                result = reader.ReadToEnd();
                reader.Close();
                response.Close();
            }
            catch
            {
            }
            return result;
        }
    }
}
